//
//  ServiceConnect.m
//  ExternalCommonLibrary
//
//  Created by goldeney on 15/1/6.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "ServiceConnect.h"
#import "ServiceArgs.h"
#import "AESCrypt.h"
#import "HttpNativeConnect.h"

@interface ServiceConnect()

@property (nonatomic, strong) MBProgressHUD *mbProgressHUD;
@property (nonatomic, assign) BOOL showNetworkPrompt;

@property (nonatomic, strong) ServiceHelper *helper;
@property (nonatomic, strong) ServiceArgs *serviceArgs;

@end

@implementation ServiceConnect
@synthesize delegate = _delegate;
@synthesize mbProgressHUD = _mbProgressHUD;
@synthesize helper = _helper;
@synthesize showNetworkPrompt = _showNetworkPrompt;
@synthesize serviceArgs = _serviceArgs;

#pragma mark -单例模式
//static NSMutableArray *serviceConnectArray;

- (id)initWithMethodName:(NSString*)methodName dataArray:(ServiceParametModel*)para
{
    return [self initWithMethodName:methodName dataArray:para URL:nil];
}

- (id)initWithMethodName:(NSString*)methodName dataArray:(ServiceParametModel*)para URL:(NSString*)url
{
    self = [super init];
    if (self) {
//        if (!serviceConnectArray) serviceConnectArray = [[NSMutableArray alloc] init];
//        [serviceConnectArray addObject:self];
        
        self.helper = [[ServiceHelper alloc] init];
        self.serviceArgs = [[ServiceArgs alloc] init];
        
        NSString *newUrl = nil;
        if (url && url.length>0) {
            newUrl = [NSString stringWithFormat:@"%@%@",url,defaultWebServiceUrl];
        } else {
            ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
            newUrl = [NSString stringWithFormat:@"%@%@",model.IpAddress,defaultWebServiceUrl];
        }
        
        [_serviceArgs setWebURL:[NSURL URLWithString:newUrl]];
        [_serviceArgs setServiceURL:[NSURL URLWithString:newUrl]];
        [_serviceArgs setServiceNameSpace:defaultWebServiceNameSpace];
        [_serviceArgs setServiceGUID:defaultWebServiceGUID];
        [_serviceArgs serviceMethodName:methodName soapParametModel:para];
    }
    return self;
}

- (void)dealloc
{
    if(_helper) {
        [_helper.httpRequest cancel];
        [_helper.httpRequest clearDelegatesAndCancel];
    }
    
    _helper = nil;
    _delegate = nil;
    _mbProgressHUD = nil;
}

#pragma mark -
#pragma mark 请求数据方法

//同步请求数据
- (ServiceResultModel*) startSyncConnectNetworkGetData
{
    return [_helper syncService:self.serviceArgs];
}

//异步请求数据
-(void)startConnectNetworkGetData
{
    [_helper asynService:self.serviceArgs delegate:self];
}

//异步请求数据
-(void)startConnectNetworkCompleted:(finishBlockRequest)finish failed:(failedBlockRequest)failed abnormal:(abnormalBlockRequest)abnormal
{
    //连接类型 0-Webserver 1-javaweb
    ConfigurationCodeing *configuration = [ConfigurationHelper getConfigurationData];
    if([configuration.serverType integerValue] == 0){
        [self webServerHttpRequestParam:self.serviceArgs completed:finish failed:failed abnormal:abnormal];
    } else if([configuration.serverType integerValue] == 1) {
        [self javaHttpRequestParam:self.serviceArgs completed:finish failed:failed];
    }
}

//异步请求数据，含有进度条
-(void)startConnectNetworkGetDataProgress:(UIView*)view labelText:(NSString*)labelText
{
    [self showMBProgressHUD:view labelText:labelText];
    [self startConnectNetworkGetData];
}

//队列请求数据（暂未测试）
-(void) startQueueConnectNetworkGetData
{
    ServiceHelper *helper = [ServiceHelper sharedInstance];
    
    //添加队列
    ASIHTTPRequest *request1=[ServiceHelper commonSharedRequest:self.serviceArgs];
    [request1 setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"request1",@"name", nil]];
    [helper addQueue:request1];
    [helper startQueue:self];
    
}

#pragma mark WebServer平台异步请求数据

-(void)webServerHttpRequestParam:(ServiceArgs*)args completed:(finishBlockRequest)finish failed:(failedBlockRequest)failed abnormal:(abnormalBlockRequest)abnormal
{
    [_helper asynService:args completed:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(finish) finish(result,userInfo);
        //        if (serviceConnectArray) [serviceConnectArray removeObject:self];//移除占用
        //关闭进度条
        if (_mbProgressHUD){
            [_mbProgressHUD hide:YES];
            [_mbProgressHUD removeFromSuperview];
            _mbProgressHUD = nil;
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        if(failed) failed(error,userInfo);
        //        if (serviceConnectArray) [serviceConnectArray removeObject:self];//移除占用
        //关闭进度条
        if (_mbProgressHUD){
            [_mbProgressHUD hide:YES];
            [_mbProgressHUD removeFromSuperview];
            _mbProgressHUD = nil;
        }
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        if(abnormal) abnormal(error,userInfo);
        //        if (serviceConnectArray) [serviceConnectArray removeObject:self];//移除占用
        //关闭进度条
        if (_mbProgressHUD){
            [_mbProgressHUD hide:YES];
            [_mbProgressHUD removeFromSuperview];
            _mbProgressHUD = nil;
        }
    }];
}

#pragma mark JAVA平台异步请求数据

-(void)javaHttpRequestParam:(ServiceArgs*)args completed:(finishBlockRequest)finish failed:(failedBlockRequest)failed
{
    HttpInputRequest *request = [[HttpInputRequest alloc] init];
    [request setInterface:args.methodName];
    [request setIntType:InterfaceTypeGIM];
    [request setConnectType:WebServerConnectType];
    
    NSArray *parametArray = [args.parametModel getValueArray];
    for (NSDictionary *item in parametArray) {
        id key = [[item allKeys] objectAtIndex:0];
        [request setParameterVale:[item objectForKey:key] key:key];
    }
    
    //请求接口数据
    [[HttpNativeConnect shareInstance] requestWithParams:request success:^(HttpOutputResult *responseObject) {
        //这里处理只有一张表的情况
        NSArray *response = responseObject.objectArray;
        if(responseObject.objectArray.count == 1){
            response = [responseObject objectTableFirst];
        }
        //返回处理后的数据
        ServiceResultModel *model = [[ServiceResultModel alloc] init];
        model.statusCode = 200;
        model.resultArray = response;
        finish(model, nil);
    } failure:^(NSError * _Nonnull error) {
        failed(error, error.userInfo);
    }];
}

#pragma mark - 取消连接
- (void)cancel
{
    if(_helper) {
        [_helper.httpRequest cancel];
        [_helper.httpRequest clearDelegatesAndCancel];
    }
    
    //移除占用
//    if (serviceConnectArray)
//        [serviceConnectArray removeObject:self];
}

#pragma mark -
#pragma mark ServiceHelperDelegate

-(void)progressRequest:(ASIHTTPRequest*)request
{
    
}

-(void)finishSoapRequest:(id)xml userInfo:(NSDictionary*)userInfo
{
    if (_delegate != nil) [_delegate finishSoapRequest:xml userInfo:userInfo];
    if (_mbProgressHUD){
        [_mbProgressHUD hide:YES];
        [_mbProgressHUD removeFromSuperview];
        _mbProgressHUD = nil;
    }
    
    //移除占用
//    if (serviceConnectArray)
//    [serviceConnectArray removeObject:self];
}

-(void)abnormalRequest:(NSError*)error userInfo:(NSDictionary*)userInfo
{
    if (_showNetworkPrompt) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"没有连接网络，请检查网络是否连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
    }
    
    if (_delegate != nil) [_delegate abnormalRequest:error userInfo:userInfo];
    if (_mbProgressHUD){
        [_mbProgressHUD hide:YES];
        [_mbProgressHUD removeFromSuperview];
        _mbProgressHUD = nil;
    }
    
    //移除占用
//    if (serviceConnectArray)
//        [serviceConnectArray removeObject:self];
}

-(void)failedSoapRequest:(NSError*)error userInfo:(NSDictionary*)userInfo
{
    if (_delegate != nil) [_delegate failedSoapRequest:error userInfo:userInfo];
    if (_mbProgressHUD){
        [_mbProgressHUD hide:YES];
        [_mbProgressHUD removeFromSuperview];
        _mbProgressHUD = nil;
    }
    
    //移除占用
//    if (serviceConnectArray)
//        [serviceConnectArray removeObject:self];
}

#pragma mark -
#pragma mark MBProgressHUD

- (void)showMBProgressHUD:(id)anObject labelText:(NSString*)labelText
{
    if ([anObject isKindOfClass:[UIWindow class]]) {
        UIWindow *window = anObject;
        [self showMBProgressHUD:window frame:window.bounds labelText:labelText];
        
    } else if ([anObject isKindOfClass:[UINavigationController class]]) {
        UINavigationController *controller = anObject;
        [self showMBProgressHUD:controller.view frame:controller.view.bounds labelText:labelText];
        
    } else if ([anObject isKindOfClass:[UIViewController class]]) {
        UIViewController *controller = anObject;
        CGRect frame = CGRectMake(0, 0, controller.view.bounds.size.width, controller.view.bounds.size.height);
        [self showMBProgressHUD:controller.view frame:frame labelText:labelText];
        
    } else if ([anObject isKindOfClass:[UIView class]]) {
        UIView *view = anObject;
        [self showMBProgressHUD:view frame:view.bounds labelText:labelText];
    }
}

- (void)showMBProgressHUD:(UIView*)view frame:(CGRect)frame labelText:(NSString*)labelText
{
    if (!_mbProgressHUD) {
        _mbProgressHUD = [[MBProgressHUD alloc] initWithFrame:frame];
        [view addSubview:_mbProgressHUD];
        
        //如果设置此属性则当前的view置于后台
        _mbProgressHUD.dimBackground = YES;
        if (labelText) {
            _mbProgressHUD.labelText = labelText;
        } else {
            _mbProgressHUD.labelText = @"请稍等";
        }
    }
    [_mbProgressHUD show:YES];
}

@end
